#include "toast.h"
#include <QScreen>
#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>

Toast::Toast(const QString& text)
{
    //1.设置窗口属性
    this->setFixedSize(800,150);
    this->setStyleSheet("background-color:white;");
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_DeleteOnClose);

    //2.将窗口移动到对应位置
    QScreen* screen = QApplication::primaryScreen();
    const int x = (screen->size().width()-this->width())/2;
    //消息通知toast距离底部有100的间隔
    const int y = screen->size().height()-this->height()-100;
    this->move(x,y);

    //3.在toast中添加控件
    QVBoxLayout* layout = new QVBoxLayout(this);
    QLabel* label = new QLabel;
    QFont font("微软雅黑",25);
    label->setFont(font);
    label->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    label->setText(text);
    label->setWordWrap(true);
    label->adjustSize();
    label->setAlignment(Qt::AlignCenter);
    layout->addWidget(label);

    //4.实现2s后自动消失
    QTimer* timer = new QTimer(this);
    connect(timer,&QTimer::timeout,this,[=]()
    {
        timer->stop();
        this->close();
    });
    timer->start(2000);
}


void Toast::showMessage(const QString& text)
{
    Toast* toast = new Toast(text);
    toast->show();
}
